/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
/*
 * This class is responsible for user login,logout,user register
 * 
 */
package com.mr.qa.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.io.Util;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.hibernate.Transaction;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.GlobalConfigs.UploadFileType;
import com.mr.qa.bo.Message;
import com.mr.qa.bo.MoneyReport;
import com.mr.qa.bo.User;
import com.mr.qa.bo.UserMoney;
import com.mr.qa.bo.UserMoneySpendHistory;
import com.mr.qa.bo.UserScore;
import com.mr.qa.dao.impl.AnswerDAO;
import com.mr.qa.dao.impl.MessageDAO;
import com.mr.qa.dao.impl.QuestionDAO;
import com.mr.qa.dao.impl.SharedFileDAO;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.dao.impl.UserMoneySpendHistoryDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.UserForm;
import com.mr.qa.util.ExcelRow;
import com.mr.qa.util.ExcelWriter;
import com.mr.qa.util.HibernateSessionFactory;
import com.mr.qa.util.RandomUtil;
import com.mr.qa.util.mail.Mail;
import com.mr.qa.util.mail.MailUtil;

public class UserAction extends BaseAction 
{
    private static final Log log = LogFactory.getLog(UserAction.class);
    String[] forbiddenIP = {"58.33.122.106", "58.33.123.25", "210.22.108.110", "210.22.108.105", "218.82.137.6", "218.82.142.122", "218.82.130.3","218.82.139.0"};
    /**
    * Method execute
    * 
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return ActionForward
    */
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        String forward = null;
        UserForm userForm = (UserForm)form;
        String action = getAction(request);
        String vcinSession = UserSessionUtil.getVerificationCodes(request);
        String vc = userForm.getVc();
        UserSession us = null;
        us = UserSessionUtil.getUserSession(request);
        if(vc == null)vc = "";
        String loginName = userForm.getLoginName();
        if(loginName == null)loginName = "";
        ActionForward af = null;
        int page = userForm.getPage();
        if(page == 0)page = 1;
        int pageSize = userForm.getPageSize();
        if(pageSize == 0)
        {
                if(!"myanswers".equals(action))
                    pageSize = GlobalConfigs.SIZE_USER_LIST;//user number in a user list page
                else
                    pageSize = 30;
        }
        if("login".equals(action) || "active".equals(action)) 
        {
        	if("active".equals(action)){
            	User user = active(Integer.valueOf(request.getParameter("id")));
            	messages.add("active", new ActionMessage("active.success"));
            	userForm.setName(user.getName());
            	userForm.setPassword(user.getPassword());
            	loginName = user.getLoginName();
            }
            String password = userForm.getPassword();
            if(vcinSession == null && !"active".equals(action))
            {
                errors.add("login", new ActionMessage("verificationcode.error"));
                af = mapping.findForward("relogin");
            }
            else if(loginName == null || loginName.length() == 0)//2008.3.5
            {
                errors.add("login", new ActionMessage("user.loginname.required"));
                af = mapping.findForward("relogin");
            }
            else if(password == null || password.length() == 0)//2008.3.5
            {
                errors.add("login", new ActionMessage("user.password.required"));
                af = mapping.findForward("relogin");
            }
            else if(checkIpIsForbidden(request))
            {
            	errors.add("login", new ActionMessage("commonfailmessage"));
                af = mapping.findForward("relogin");
            }
            else
            {
                if(!vc.equals(vcinSession) && !"active".equals(action))
                {
                    errors.add("login", new ActionMessage("verificationcode.error"));
                    af = mapping.findForward("relogin");
                }
                else
                {
                    Date logonDate = new Date();
                    User user = doLogin(loginName, password,logonDate);
                    if(user != null)
                    {
						String loginStyle = userForm.getLoginStyle();
						int maxAge = 2592000;// 60*60*24*30;
						if ("clean".equals(loginStyle)
								|| "no".equals(loginStyle)) {
							response.addCookie(new Cookie("loginStyle",
									loginStyle));
							response.addCookie(new Cookie("loginName", ""));
							response.addCookie(new Cookie("lastLogonTime", ""));
							response.addCookie(new Cookie("logout", ""));
						} else if ("remember".equals(loginStyle)
								|| "autoLogin".equals(loginStyle)) {
							Cookie loginNameCookie = new Cookie("loginName",
									loginName);
							loginNameCookie.setMaxAge(maxAge);
							response.addCookie(loginNameCookie);

							Cookie loginStyleCookie = new Cookie("loginStyle",
									loginStyle);
							loginStyleCookie.setMaxAge(maxAge);
							response.addCookie(loginStyleCookie);

							Cookie lastLogonDateCookie = new Cookie(
									"lastLogonTime", "" + logonDate.getTime());
							lastLogonDateCookie.setMaxAge(maxAge);
							response.addCookie(lastLogonDateCookie);

							response.addCookie(new Cookie("logout", ""));
						}
						printlnCookies("userAction", request);
						us = new UserSession();
						UserSessionUtil.transferUserToUserSession(user, us);
						UserSessionUtil.saveUserSession(us, request);

						if (!"active".equals(action)) {
							String originalUrl = userForm.getOriginalUrl();
							if (originalUrl == null)
								originalUrl = "";
							if (originalUrl.trim().length() > 1
									&& !(originalUrl.indexOf("action=login") > 0)) {
								// from question section
								// forward to
								originalUrl = originalUrl.replaceFirst(request
										.getContextPath(), "");
								ActionForward originalForward = new ActionForward(
										originalUrl);
								return originalForward;
							} else if (originalUrl.indexOf("action=login") > 0) {
								action = "view";
								String path = mapping.findForward(action)
										.getPath();
								af = new ActionForward(path);
								af.setRedirect(true);
								return af;
							} else // from shared file section
							{
								String referer = request.getHeader("Referer");
								boolean goRerer = goReferer(request);
								if (referer.indexOf("?") < 0) {
									goRerer = false;
								}
								if (goRerer) {
									af = new ActionForward(referer);
									af.setRedirect(true);
									return af;
								} else {
									action = "view";
									String path = mapping.findForward(action)
											.getPath();
									af = new ActionForward(path);
									af.setRedirect(true);
									return af;
								}
							}
						} else {
							action = "index";
						}
					}
                    else
                    {
                        errors.add("login", new ActionMessage(
                                                    "user.login.error"));
                        af = mapping.findForward("relogin");
                     }
                }   
            }     
        }
        else if("add".equals(action))
        {
            try
            {
                User user = checkUserByLoginName(userForm.getLoginName());
                if(user != null){
                	messages.add("",new ActionMessage("user.loginname.exist",userForm.getLoginName()));
                    action = "preadd";
                }else{
                	user = checkUserByEmail(userForm.getEmail());
                	if(user != null){
                		messages.add("",new ActionMessage("user.email.exist",userForm.getEmail()));
                        action = "preadd";
                	}else{
                		if(vcinSession == null)
                        {
                            errors.add("login", new ActionMessage("verificationcode.required"));
                            action = "preadd";
                        }
                        else if(!vcinSession.equals(userForm.getVc()))
                        {
                            errors.add("login", new ActionMessage("verificationcode.error"));
                            action = "preadd";
                        }
                        else if(checkIpIsForbidden(request))
                        {
                        	errors.add("login", new ActionMessage("commonfailmessage"));
                            action = "preadd";
                        }
                        else
                        {
                            User newUser = add(userForm);
                            log.info("User:"+userForm.getLoginName()+" registered with IP:"+request.getRemoteAddr()+" "+request.getRemoteUser());
                            messages.add("",new ActionMessage("user.register.success",userForm.getLoginName(),GlobalConfigs.HOURS_ADDQUESTION_AFTER_REGISTRATION));
                            UserSession userSession = new UserSession();
                            UserSessionUtil.transferUserToUserSession(newUser,userSession);
                            UserSessionUtil.saveUserSession(userSession,request);
                            action = "index";
                            boolean sendMailOK = sendActiveMail(newUser, request.getServerName(), false);
                            if (!sendMailOK) {
                            	errors.add("login", new ActionMessage("mail.sentfail"));
                            }
                        }
                	}
                }
            }
            catch(QaException qae)
            {
                action = "preadd";
                errors.add("",new ActionMessage("message",qae.getMessage()));
            }
        }
        else if("checkloginnameifexist".equals(action))
        {
            try
            {
                User user = checkUserByLoginName(userForm.getLoginName());
                if(user != null)request.setAttribute("loginnameused","Y");
            }
            catch(QaException qae)
            {
                log.error(qae);
            }
        }
        else if("checkemailexist".equals(action))
        {
            try
            {
            	String id = userForm.getId();
            	Integer userId = null;
            	if(id != null && id.length() > 0){
            		userId = new Integer(id);
            	}
            	User user = checkUserByEmail(userForm.getLoginName(), userId);
                if(user != null)request.setAttribute("emailused","Y");
            }
            catch(QaException qae)
            {
                log.error(qae);
            }
        }
        else if("list".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else if(!us.isAdminPasswordInput()){
            	StringBuffer uri = new StringBuffer(request.getRequestURI() + "?");
            	Enumeration paramNames = request.getParameterNames();
            	int i = 0;
            	while(paramNames.hasMoreElements()){
            		if(i != 0){
            			uri.append("&");
            		}
            		String name = (String)paramNames.nextElement();
            		uri.append(name + "=");
            		uri.append(request.getParameter(name));
            		i++;
            	}
            	request.setAttribute("preURI",uri.toString());
            	action = "adminPass";
            }
            else
            {
                int count = 0;
                List list = null;
                if(loginName != null && loginName.length() > 0)
                {
                    count = countAllUsersByLoginName(loginName);
                    list = getListByLoginName(loginName,page,pageSize);
                }
                else
                {
                    count = countAllUsers();
                    list = getList(page,pageSize);
                }
                request.setAttribute("pageSize",pageSize);//for pagination tag
                request.setAttribute("resultSize",count);//for pagination tag
                request.setAttribute("users",list);
            }
        }
        else if("disable".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                disable(userForm.getId());
                String path = mapping.findForward(action).getPath();
                af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
                af.setRedirect(true);
            }
        }
        else if("enable".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                enable(userForm.getId());
                String path = mapping.findForward(action).getPath();
                af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
                af.setRedirect(true);
            }
        }
        else if("delete".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                String deletedUserLoginName = "";
                try{
                deletedUserLoginName = delete(userForm.getId());
                errors.add("deleteuser", new ActionMessage("user.delete.success",deletedUserLoginName));
                log.info("Admin "+us.getUserId()+":"+us.getLoginName()+" deleted user "+userForm.getId()+":"+deletedUserLoginName);
                }catch(Exception e){
                    errors.add("deleteuserfail", new ActionMessage("user.delete.fail",deletedUserLoginName));                    
                }
                String path = mapping.findForward(action).getPath();
                af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
                af.setRedirect(true);
            }
        }
        else if("changetype".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                changeType(userForm.getId(),userForm.getType());
                String path = mapping.findForward(action).getPath();
                af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
                af.setRedirect(true);
            }
        }
        else if("useradmin".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                User user = get(us.getUserId());
                request.setAttribute("usero", user);
                request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
                request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
                request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            }
        }
        else if("admin".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }    
            else
            {
                if(!"1".equals(us.getType()))
                {
                    errors.add("login", new ActionMessage("admin.requireadmin"));
                    action = "relogin";
                }else if(!us.isAdminPasswordInput()){
                	StringBuffer uri = new StringBuffer(request.getRequestURI() + "?");
                	Enumeration paramNames = request.getParameterNames();
                	int i = 0;
                	while(paramNames.hasMoreElements()){
                		if(i != 0){
                			uri.append("&");
                		}
                		String name = (String)paramNames.nextElement();
                		uri.append(name + "=");
                		uri.append(request.getParameter(name));
                		i++;
                	}
                	
                	request.setAttribute("preURI",uri.toString());
                	action = "adminPass";
                }
            }   
        }
        else if("logout".equals(action))
        {
            request.getSession().invalidate();
            Cookie logoutCookie = new Cookie("logout","true");
            response.addCookie(logoutCookie);
        }
        else if("viewuserbyother".equals(action))
        {
            //how many questions listed on a page?
            int pageSizeForUserQuestion = userForm.getPageSize();
            if(pageSizeForUserQuestion == 0)
            {
                pageSizeForUserQuestion = GlobalConfigs.SIZE_QUESTION_VIEWBYOTHER_LIST;
            }
            request.setAttribute("pageSize",""+pageSizeForUserQuestion);
            request.setAttribute("resultSize",countUserQuestions(new Integer(userForm.getId())));
            request.setAttribute("userquestions",getUserQuestions(new Integer(userForm.getId()),page,pageSizeForUserQuestion));
            countHisQuestionAnswer(request, Integer.valueOf(userForm.getId()));
        }
        else if("viewsharedfilesbyother".equals(action))
        {
            countHisQuestionAnswer(request, Integer.valueOf(userForm.getId()));
        }
        else if("viewmysharedfiles".equals(action))
        {
            request.setAttribute("usero",get(us.getUserId()));
            request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
            request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
            request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
        }
        else if("mylinks".equals(action))
        {
            request.setAttribute("usero",get(us.getUserId()));
            request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
            request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
            request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
        }
        else if("myspend".equals(action))
        {
            request.setAttribute("usero",get(us.getUserId()));
            request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
            request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
            request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            getSpendMoney(us.getUserId(), request, page, pageSize);
        }
        else if("myaward".equals(action))
        {
            request.setAttribute("usero",get(us.getUserId()));
            request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
            request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
            request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            getAwardMoney(us.getUserId(), request, page, pageSize);
        }
        else if("viewspendbyother".equals(action)){
        	countHisQuestionAnswer(request, Integer.valueOf(userForm.getId()));
        	getSpendMoney(Integer.valueOf(userForm.getId()), request, page, pageSize);
        }
        else if("viewawardbyother".equals(action)){
        	countHisQuestionAnswer(request, Integer.valueOf(userForm.getId()));
        	getAwardMoney(Integer.valueOf(userForm.getId()), request, page, pageSize);
        }
        else if("prechangepassword".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }    
        }
        else if("changepassword".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                if(vc.length() == 0)
                {
                    errors.add("login", new ActionMessage("verificationcode.required"));
                    forward = "prechangepassword";
                }
                else if(!vc.equals(vcinSession))
                {
                    errors.add("login", new ActionMessage("verificationcode.error"));
                    action = "prechangepassword";
                }
                else
                {
                    String oldPassword = request.getParameter("opassword");
                    int result = this.changePassword(us.getUserId(),userForm.getPassword(),oldPassword);
                    if(result == 0)
                    {
                        errors.add("nouser", new ActionMessage("nouser"));
                        action = "prechangepassword";
                    }
                    else if(result == 2)
                    {
                        errors.add("",new ActionMessage("oldpassword.error"));
                        action = "prechangepassword";
                    }
                    else if(result == 1)
                    {
                        messages.add("",new ActionMessage("message","Password changed"));
                    }
                }
            }
        }
        else if("changeuserprofile".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                if(vc.length() == 0)
                {
                    errors.add("login", new ActionMessage("verificationcode.required"));
                    af = new ActionForward();
                    af.setPath("/user.mrqa?action=prechangeuserprofile");
                    af.setRedirect(true);
                }
                else if(!vc.equals(vcinSession))
                {
                    errors.add("login", new ActionMessage("verificationcode.error"));
                    af = new ActionForward();
                    af.setPath("/user.mrqa?action=prechangeuserprofile");
                    af.setRedirect(true);
                }
                else
                {
                	User user = checkUserByEmail(userForm.getEmail(), new Integer(userForm.getId()));
                	if(user != null){
                		errors.add("", new ActionMessage("user.email.exist", userForm.getEmail()));
                        af = new ActionForward();
                        af.setPath("/user.mrqa?action=prechangeuserprofile");
                        af.setRedirect(true);
                	}else{
                        int result = this.changeUserProfile(userForm);
                        if(result == 0)
                        {
                            errors.add("relogin", new ActionMessage("message","no user exists"));
                        }
                        else if(result == 1)
                        {
                            request.setAttribute("usero",get(new Integer(userForm.getId())));
                            messages.add("",new ActionMessage("message","Profile changed"));
                        }
                        else if(result == 2)
                        {
                        	User userUpdated = get(new Integer(userForm.getId()));
                        	request.setAttribute("usero", userUpdated);
                            messages.add("email.changed",new ActionMessage("email.changed"));
                            boolean sendMailOK = sendActiveMail(userUpdated, request.getServerName(), false);
                            if (!sendMailOK) {
                            	errors.add("login", new ActionMessage("mail.sentfail"));
                            }
                        }
                	}
                }
            }
        }
        else if("myanswers".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                request.setAttribute("usero",get(us.getUserId()));
                List list = findMyAnswers(us.getUserId(),page,30);
                //System.out.println("myanswers list.size="+list.size());
                request.setAttribute("myanswers",list);
                int resultSize = countMyAnswers(us.getUserId());
                //System.out.println("myanswers resultSize="+resultSize);
                request.setAttribute("resultSize",resultSize);
                request.setAttribute("pageSize",pageSize);
                request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
                request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
                request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            }
        }
        else if("myquestions".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                request.setAttribute("usero",get(us.getUserId()));
                request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
                request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
                request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            }
        }
        else if("mylinks".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                request.setAttribute("usero",get(us.getUserId()));
                request.setAttribute("questionCount", countMyQuestions(us.getUserId()));
                request.setAttribute("answerCount", countMyAnswers(us.getUserId()));
                request.setAttribute("sfCount", countMyShareFile(us.getUserId()));
            }
        }
        else if("viewanswersbyother".equals(action))
        {
                pageSize = 30;
                List list = findUserAnswers(new Integer(userForm.getId()),page,pageSize);
                request.setAttribute("myanswers",list);
                int resultSize = countUserAnswers(new Integer(userForm.getId()));
                request.setAttribute("resultSize",resultSize);
                request.setAttribute("pageSize",pageSize);
                countHisQuestionAnswer(request, Integer.valueOf(userForm.getId()));
        }
        else if("prechangeuserprofile".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else
            {
                User user = get(us.getUserId());
                //us.setLoginName(user.getLoginName());
                request.setAttribute("usero",user);
            }    
        }
        else if("findpasswordresult".equals(action))
        {
        }
        else if("resetpassword".equals(action))
        {
        }
        else if("simplyresetpassword".equals(action))
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                simplyResetPassword(new Integer(userForm.getId()));
                errors.add("passwordreset", new ActionMessage("user.password.reset.success"));
            }
            String path = mapping.findForward(action).getPath();
            af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
            af.setRedirect(true);
        }
        else if("findpasswordstep2".equals(action))
        {
            String findPasswordStyle = userForm.getFindPasswordStyle();
            if("1".equals(findPasswordStyle))
            //get question
                af = findPasswordStep2(mapping,userForm,errors,request);
            else if("2".equals(findPasswordStyle))
                af = sendPasswordMail(userForm,mapping,errors,messages,request);
        }
        else if("findpasswordstep3".equals(action))
        {
            //validate answer
            af = findPasswordStep3(mapping,userForm,errors,request);
        }
        else if("findpasswordstep4".equals(action))
        {
            //reset password
            af = findPasswordStep4(mapping,userForm,errors,request);
        }
        else if("setuserassuper".equals(action))
        {
            //reset password
            af = setUserAsSuper(mapping,userForm,errors,request);
            String path = mapping.findForward(action).getPath();
            af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
            af.setRedirect(true);
        }
        else if("excel".equals(action))//2008.3.7
        {
            if(us == null)
            {
                errors.add("relogin", new ActionMessage("login.required"));
                action = "relogin";
            }
            else if(!"1".equals(us.getType()))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition","attachment;filename=userlist.xls");
                OutputStream os = response.getOutputStream();
                createUsersExcel(os);
                os.flush();
                os.close();
            }
        }
        else if("prohibit".equals(action))
        {
            if(GlobalConfigs.PROHIBITED_USERS == null)
            GlobalConfigs.PROHIBITED_USERS = "";
            GlobalConfigs.PROHIBITED_USERS += userForm.getId()+",";
            disable(userForm.getId());
            String path;
            path = mapping.findForward(action).getPath();
            af = new ActionForward();
            af.setPath(path+"&id="+userForm.getId());
            af.setRedirect(true);
        }
        else if("preadminmodifyuser".equals(action))
        {
            if(us == null || !us.getType().equals("1"))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                request.setAttribute("usero",get(new Integer(userForm.getId())));
            }
        }
        else if("adminmodifyuser".equals(action))
        {
            if(us == null || !us.getType().equals("1"))
            {
                errors.add("noright", new ActionMessage("user.noright"));
                action = "error";
            }
            else
            {
                modifyUserByAdmin(mapping,userForm,errors,request);
                if(errors.size() > 0)
                {
                    request.setAttribute("usero",get(new Integer(userForm.getId())));
                    action = "preadminmodifyuser";
                }
                else
                {
                    String path = mapping.findForward(action).getPath();
                    af = new ActionForward(path+"&page="+page+"&loginName="+loginName);
                    af.setRedirect(true);
                }
            }
        }else if("uploadHeader".equals(action)){
        	Integer id = addHeaderImage(userForm, errors);
        }else if("loginadmin".equals(action)){
        	String password = userForm.getAdminPassword();
            if(!password.equals(GlobalConfigs.ADMIN_PASSWORD)){
            	errors.add("login", new ActionMessage("admin.password.incorrect"));
            	request.setAttribute("preURI", userForm.getPreURI());
            	action="adminPass";
            }else{
            	UserSessionUtil.setAdminPasswordInput(true, us);
            	UserSessionUtil.saveUserSession(us, request);
            	af = new ActionForward(userForm.getPreURI());
                af.setRedirect(true);
            }
        }else if("sendactivemail".equals(action))
        {
            try
            {
            	String id = userForm.getId();
            	Integer userId = null;
            	if(id != null && id.length() > 0){
            		userId = new Integer(id);
            	}
            	
            	boolean sendOK = sendActiveMailInModify(userForm.getEmail(), Integer.valueOf(userForm.getId()), request.getServerName());
            	if (sendOK){
            		messages.add("",new ActionMessage("user.send.active.mail",""));
            	} else {
            		errors.add("login", new ActionMessage("mail.sentfail"));
            	}
            }
            catch(QaException qae)
            {
                log.error(qae);
            }
        }
        if(errors.size() > 0)
        {
            saveErrors(request.getSession(), errors);
            saveErrors(request, errors);
        }
        if(messages.size() > 0)
        {
            saveMessages(request.getSession(), messages);
            saveMessages(request, messages);
        }
        if(af == null)
            return mapping.findForward(action);
        else
            return af;
    }

    
    private ActionForward modifyUserByAdmin(ActionMapping mapping, 
                        ActionForm form,ActionMessages errors,
                        HttpServletRequest request) throws QaException
    {
        UserForm userForm = (UserForm)form;
        String id = userForm.getId();
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(new Integer(id));
            user.setIsSuper(userForm.getIsSuper());
            user.setType(userForm.getType());
            user.setState(userForm.getState());
            user.setPermissions(userForm.getPermissions());
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null) 
              tx.rollback();
            errors.add("", new ActionMessage("message",e.getMessage()));
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
        return mapping.findForward(this.getAction(request));
    }


    /**
     * set the user as super
     * @param mapping
     * @param form
     * @param errors
     * @param request
     * @return
     * @throws QaException
     */
    private ActionForward setUserAsSuper(ActionMapping mapping, 
                        ActionForm form,ActionMessages errors,
                        HttpServletRequest request) throws QaException
    {
        UserForm userForm = (UserForm)form;
        String id = userForm.getId();
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(new Integer(id));
            user.setIsSuper(userForm.getIsSuper());
            tx.commit();
        }
        catch(Exception e)
        {
            if(tx != null) 
              tx.rollback();
            errors.add("", new ActionMessage("message",e.getMessage()));
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
        return mapping.findForward(this.getAction(request));
    }

    /**
     * find password question by user login name
     * @param mapping
     * @param form
     * @param errors
     * @param request
     * @return
     * @throws QaException
     */
    private ActionForward findPasswordStep2(ActionMapping mapping, 
                        ActionForm form,ActionMessages errors,
			HttpServletRequest request) throws QaException
    {
        UserForm userForm = (UserForm)form;
        String vcinSession = UserSessionUtil.getVerificationCodes(request);
        String vc = userForm.getVc();
        if(vc == null)
        {
            errors.add("findpassword", new ActionMessage("verificationcode.required"));
            return mapping.findForward("findpasswordstep1");
        }
        if(!vc.equals(vcinSession))
        {
            errors.add("findpassword", new ActionMessage("verificationcode.error"));
            return mapping.findForward("findpasswordstep1");
        }
        String loginName = userForm.getLoginName();
        if(loginName == null || loginName.length() == 0)
        {
            errors.add("findpassword", new ActionMessage("user.loginname.required"));
            return mapping.findForward("findpasswordstep1");
        }
        User user = this.checkUserByLoginName(loginName);
        if(user == null)
        {
            errors.add("findpassword", new ActionMessage("nouser"));
            return mapping.findForward("findpasswordstep1");
        }
        request.setAttribute("userobj",user);
        userForm.setPasswordQuestion(user.getPasswordQuestion());
        userForm.setId(user.getId()+"");
        request.getSession().setAttribute("findpasswordstep","2");
        return mapping.findForward("findpasswordstep2");
    }

    /**
     * match password answer entered with persistent
     * @param mapping
     * @param form
     * @param errors
     * @param request
     * @return
     * @throws QaException
     */
    private ActionForward findPasswordStep3(ActionMapping mapping, 
                        ActionForm form,ActionMessages errors,
                        HttpServletRequest request) throws QaException
    {
        UserForm userForm = (UserForm)form;
        String id = userForm.getId();
        String passwordAnswer = userForm.getPasswordAnswer();
        if(passwordAnswer == null || passwordAnswer.length() == 0)
        {
            errors.add("findpassword", new ActionMessage("user.loginname.required"));
            return mapping.findForward("findpasswordstep2");
        }
        if(id == null || id.length() == 0)
        {
            return mapping.findForward("findpasswordstep1");
        }
        User user = this.get(new Integer(id));
        request.setAttribute("userobj",user);
        if(passwordAnswer.equals(user.getPasswordAnswer()))
        {
            request.getSession().setAttribute("findpasswordstep","3");
            return mapping.findForward("findpasswordstep3");
        }
        else
        {
            errors.add("findpassword", new ActionMessage("user.passwordanswer.notmatch"));
            return mapping.findForward("findpasswordstep2");
        }
    }
    //reset password
    private ActionForward findPasswordStep4(ActionMapping mapping, 
                        ActionForm form,ActionMessages errors,
                        HttpServletRequest request) throws QaException
    {
        UserForm userForm = (UserForm)form;
        String id = userForm.getId();
        String password = userForm.getPassword();
        if(id == null || id.length() == 0)
        {
            return mapping.findForward("findpasswordstep1");
        }
        if(password == null || password.length() == 0)
        {
            errors.add("findpassword", new ActionMessage("user.password.required"));
            return mapping.findForward("findpasswordstep3");
        }
        User user = this.get(new Integer(id));
        String oldPassword = user.getPassword();
        this.changePassword(user.getId(),password,oldPassword);
        request.setAttribute("directLogin","yes");
        return mapping.findForward("findpasswordstep4");        
    }


    /**
     * send simple mail incuding username and password
     * @param UserForm
     */
    private ActionForward sendPasswordMail(UserForm userForm,ActionMapping mapping,ActionMessages errors,ActionMessages messages,HttpServletRequest request)
    {
        String userLoginName = userForm.getLoginName();   
        String vcinSession = UserSessionUtil.getVerificationCodes(request);
        String vc = userForm.getVc();
        if(vc == null)
        {
            errors.add("findpassword", new ActionMessage("verificationcode.required"));
            return mapping.findForward("findpasswordstep1");
        }
        if(!vc.equals(vcinSession))
        {
            errors.add("findpassword", new ActionMessage("verificationcode.error"));
            return mapping.findForward("findpasswordstep1");
        }
        if(userLoginName == null || userLoginName.trim().length() == 0)
        {
            errors.add("findpassword", new ActionMessage("user.loginname.required"));
            return mapping.findForward("findpasswordstep1");
        }
        try
        {
            User user = this.checkUserByLoginName(userLoginName);
            if(user == null)//nouser
            {
                errors.add("findpassword", new ActionMessage("nouser"));
                return mapping.findForward("findpasswordstep1");
            }
            else
            {
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("mailtemplate.properties");
                Properties ps = new Properties();
                ps.load(is);
                String from = "service@mainframer.cn";
                String to = user.getEmail();
                String subject = ps.getProperty("pm.subject");
                StringBuffer sb = new StringBuffer();
                sb.append("<html>");
                sb.append("<head>");
                sb.append("<meta http-equiv='Content-Type' content='text/html;charset=GBK'>");
                sb.append("</head>");
                sb.append("<body>");
                sb.append("<div style='width:450;'>");
                sb.append("<img src='http://www.mainframer.cn/images/default_02.gif'/><br>");
                sb.append("<hr size='1'>");
                sb.append(ps.getProperty("pm.body.1"));
                sb.append(ps.getProperty("pm.body.2").replaceFirst("\\{0\\}",to));
                sb.append(ps.getProperty("pm.body.3").replaceAll("\\{0\\}",user.getLoginName()));
                sb.append(ps.getProperty("pm.body.4").replaceAll("\\{0\\}",user.getPassword()));
                sb.append(ps.getProperty("pm.body.5"));
                sb.append(ps.getProperty("pm.body.6"));
                sb.append("<hr>");
                sb.append(ps.getProperty("pm.body.7"));
                sb.append("</div>");
                sb.append("</body>");
                sb.append("</html>");
                String body = sb.toString();
                //body = new String(body.getBytes("8859_1"));
                //body = MimeUtility.decodeText(body);
                /*
                String body = "mainframer user:"+user.getLoginName()+",password:"+user.getPassword()+"\n";
                body += "Don't reply to this mail,Welcome to www.mainframer.cn for more\n";
                */
                Mail mail = new Mail();
                mail.setFrom(from);
                mail.setTo(to);
                mail.setSubject(subject);
                //log.info("mail subject1="+mail.getSubject());
                mail.setBody(body);
                //MailUtil.sendServiceSimpleMailWithAttachment(mail);
                MailUtil.sendServiceSimpleHtmlMail(mail);
                messages.add("findpassword", new ActionMessage("sendpasswordmail.success"));
                log.info("user "+user.getId()+":"+user.getLoginName()+" found password by mail "+to);
            }
        }
        catch(QaException qe)
        {
            log.error("Encounter:"+qe+" when send password mail");
            if("mail-1".equals(qe.getCode()))
                errors.add("findpassword", new ActionMessage("findpassword.failure.invalidmail"));
            else
                errors.add("findpassword", new ActionMessage("nouser"));
        }
        catch(Exception e)
        {
            log.error("Encounter:"+e+" when send password mail");
            errors.add("findpassword", new ActionMessage("nouser"));
        }
        return mapping.findForward("findpasswordstep1");
    }
    
    /**
     * reset user's password
     * @param userId
     * @return int 0 no user, 1 chang ok
     * @throws QaException
     */
    private int simplyResetPassword(Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();            
            tx = HibernateSessionFactory.getSession().beginTransaction();            
            User user = userDAO.findById(userId);
            if(user == null)return 0;
            String newPassword = "123456";
            user.setPassword(newPassword);
            userDAO.update(user);
            tx.commit();
        }
        catch (Exception  re)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(re);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
        return 1;
    }
    
    
    /**
     * reset user's password
     * @param userId
     * @return int 0 no user, 1 chang ok
     * @throws QaException
     */
    private int resetPassword(Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();            
            tx = HibernateSessionFactory.getSession().beginTransaction();            
            User user = userDAO.findById(userId);
            if(user == null)return 0;
            String newPassword = RandomUtil.getRandomString();            
            user.setPassword(newPassword);
            userDAO.update(user);
            tx.commit();
            /*
            sendPasswordMail(user.getEmail(),"login name:"+user.getLoginName()
            +"\n"+"password:"+newPassword+"\n");
            */
        }
        catch (Exception  re)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(re);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
        return 1;
    }

    private Integer countUserQuestions(Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            QuestionDAO questionDAO = new QuestionDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = questionDAO.countUserQuestions(userId);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }
    
    private Integer countMyQuestions(Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            QuestionDAO questionDAO = new QuestionDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = questionDAO.countMyQuestions(userId);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }

    /**
     * 2009.1.1 22:00 
     * not used currently
     * @throws QaException
     */
    private void updateUserCountsOfQuestionsAndAnswers() throws QaException
    {
        //1 get all users
        //for, to update
         Transaction tx = null;
        try 
        {
            QuestionDAO questionDAO = new QuestionDAO();
            AnswerDAO answerDAO = new AnswerDAO();
            UserDAO userDAO = new UserDAO();
            List<User> users = userDAO.getList();
            int questionsCount = 0;
            int answersCount = 0;
            for(User user:users) 
            {
                questionsCount = questionDAO.countUserQuestions(user.getId());
                answersCount = answerDAO.countUserAnswers(user.getId());
                user.setQuestionsCount(questionsCount);
                user.setAnswersCount(answersCount);
            }
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when getUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        

    }

    private List getUserQuestions(Integer userId,int page,int pageSize) throws QaException
    {
        Transaction tx = null;
        try
        {
            tx = HibernateSessionFactory.getSession().beginTransaction();
            QuestionDAO questionDAO = new QuestionDAO();
            questionDAO.setPage(page,pageSize);
            List list = questionDAO.findUserQuestions(userId);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when getUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
                
    }

    private int countUserAnswers(Integer userId) throws QaException
    {
        Transaction tx = null;
        try
        {
            AnswerDAO answerDAO = new AnswerDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = answerDAO.countUserAnswers(userId);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }


    private int countMyAnswers(Integer userID) throws QaException
    {
        Transaction tx = null;
        try
        {
            AnswerDAO answerDAO = new AnswerDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = answerDAO.countMyAnswers(userID);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }
    //viewed by other person
    private List findUserAnswers(Integer userId,int page,int pageSize) throws QaException
    {
        Transaction tx = null;
        try
        {
            AnswerDAO answerDAO = new AnswerDAO();
            answerDAO.setPage(page,pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = answerDAO.findUserAnswers(userId);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            log.error("e="+e);
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }
    //viewed by self
    private List findMyAnswers(Integer userId,int page,int pageSize) throws QaException
    {
        Transaction tx = null;
        try
        {
            AnswerDAO answerDAO = new AnswerDAO();
            answerDAO.setPage(page,pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = answerDAO.findMyAnswers(userId);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            log.error("e="+e);
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }


    /**
     * get user by id
     * @param id
     * @return
     * @throws QaException
     */
    public User get(int id) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(new Integer(id));
            tx.commit();
            return user;
        }
        catch(Exception e)
        {
            if(tx != null) 
              tx.rollback();
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }

    /**
     * get user by id for com.mr.qa.filter.QaAppFilter to update user session info
     * @param id
     * @return
     * @throws QaException
     */
    public User getForUodateUserSession(int id) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(new Integer(id));
            user.getNewMessages().size();
            tx.commit();
            return user;
        }
        catch(Exception e)
        {
            if(tx != null) 
              tx.rollback();
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }        
    }        

    private void enable(String id) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();             
            User user = userDAO.findById(new Integer(id));
            user.setState("0");
            userDAO.update(user);
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
    }        
    
    private String delete(String id) throws QaException
    {
        Transaction tx = null;
        String userLoginName = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();             
            User user = userDAO.findById(new Integer(id));
            userLoginName = user.getLoginName();
            userDAO.delete(user);
            //delete the user's questions and answers
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();
            log.error("delete a user exception:"+e);
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
        return userLoginName;
    }        
    
    
    private void disable(String id) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();             
            User user = userDAO.findById(new Integer(id));
            user.setState("1");
            userDAO.update(user);
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }            
        
    }
        
    private void changeType(String id,String type) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            User user = userDAO.findById(new Integer(id));
            if("0".equals(type))
                user.setType("1");
            if("1".equals(type))
                user.setType("0");
            userDAO.update(user);
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
    }
    
    /**
     * get the number of all users for pagination
     * @return
     * @throws QaException
     */
    private int countAllUsers() throws QaException
    {
        Transaction tx = null;
        int count = 0;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            count = userDAO.countAllUsers();                
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
        return count;
    }

    /**
     * returns all users by loginName
     * @return
     * @throws QaException
     */
    private List getListByLoginName(String loginName,int pageNo,int pageSize) throws QaException
    {
        Transaction tx = null;
        try
        {
            UserDAO userDAO = new UserDAO();
            userDAO.setPage(pageNo,pageSize);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list = userDAO.getListByLoginName(loginName);
            tx.commit();
            return list;
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
    }

    /**
     * get the number of all users searched by loginName for pagination
     * @return int
     * @throws QaException
     */
    private int countAllUsersByLoginName(String loginName) throws QaException
    {
        Transaction tx = null;
        int count = 0;
        try
        {
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            count = userDAO.countAllUsersByLoginName(loginName);
            tx.commit();
        }
        catch(Exception e)
        {
            if (tx != null)tx.rollback();            
            throw new QaException(e);
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }            
        return count;
    }

    
        /**
         * returns all users
         * @return
         * @throws QaException
         */
        private List getList(int pageNo,int pageSize) throws QaException
        {
            Transaction tx = null;
            try
            {
                UserDAO userDAO = new UserDAO();
                userDAO.setPage(pageNo,pageSize);
                tx = HibernateSessionFactory.getSession().beginTransaction();
                List list = userDAO.getList();
                tx.commit();
                return list;
            }
            catch(Exception e)
            {
                if (tx != null)tx.rollback();            
                throw new QaException(e);
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }            
        }
        
        private User checkUserByLoginName(String loginName) throws QaException
        {
            try
            {
                UserDAO userDAO = new UserDAO();
                List list = userDAO.findByLoginName(loginName);
                if(list.size() > 0)return (User)list.get(0);
                else return null;
            }
            catch(Exception e)
            {
                throw new QaException(e);
            }
        }
	
        private int changeUserProfile(UserForm userForm) throws QaException
        {
            Transaction tx = null;
            String originalEmail = null;
            try
            {
                UserDAO userDAO = new UserDAO();
                User user = userDAO.findById(new Integer(userForm.getId()));
                if(user == null)
                {
                    return 0;
                }
                else
                {
                    user.setPasswordQuestion(userForm.getPasswordQuestion());
                    user.setPasswordAnswer(userForm.getPasswordAnswer());
                    user.setName(userForm.getName());
                    user.setMobile(userForm.getMobile());
                    originalEmail = user.getEmail();
                    if (!userForm.getEmail().equals(originalEmail)) {
                    	user.setIsActive(false);
                    }
                    user.setEmail(userForm.getEmail());
                    user.setSignature(userForm.getSignature());
                    user.setIsEmailPublic(userForm.getIsEmailPublic());
                    user.setGroup(userForm.getGroup());
                    String userTitle = userDAO.selectUserTitle(user.getUserScore().getTotalScore(),user.getGroup());
                    user.getUserScore().setTitle(userTitle);
                    user.setLastLoginDate(new Date());
                    tx = HibernateSessionFactory.getSession().beginTransaction();                    
                    userDAO.update(user);
                    tx.commit();
                }
            }
            catch(Exception e)
            {
                if(tx != null)tx.rollback();
                throw new QaException(e);
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
            if (!userForm.getEmail().equals(originalEmail)) return 2;
            return 1;
        }
        
        /*
         * a user registers in person
         */
        private User add(UserForm userForm) throws QaException
        {
            Transaction tx = null;
            User user = null;
            try
            {
                user = new User();
                user.setLoginName(userForm.getLoginName());
                user.setPassword(userForm.getPassword());
                user.setPasswordQuestion(userForm.getPasswordQuestion());
                user.setPasswordAnswer(userForm.getPasswordAnswer());
                user.setName(userForm.getName());
                user.setMobile(userForm.getMobile());
                user.setEmail(userForm.getEmail());
                user.setSignature(userForm.getSignature());
                user.setType("0");
                user.setState("0");
                user.setIsSuper(false);
                user.setIsEmailPublic(userForm.getIsSuper());
                String group = userForm.getGroup();
                if(group == null)
                    throw new QaException("User Group Is Required.");
                if("APSPBA".indexOf(group) < 0)
                    throw new QaException("User Group Is Invalid.");
                user.setGroup(group);
                Date date = new Date();
                user.setRegisterDate(date);
                user.setLastLoginDate(date);
                UserScore score = new UserScore();
                score.setTitle("");
                score.setTotalScore(0);
                user.setUserScore(score);
                score.setMrIaskUser(user);
                user.setUserScore(score);
                user.setAnswersCount(0);
                user.setQuestionsCount(0);
                user.setIsActive(false);
                tx = HibernateSessionFactory.getSession().beginTransaction();
                UserDAO userDAO = new UserDAO();
                userDAO.save(user);
                userDAO.addScoreHistory(user,user.getId(),"","register","register");
                tx.commit();
            }
            catch(QaException qae)
            {
                log.error("add a new user loginname="+userForm.getLoginName()+", enter exeception:"+qae);
                if(tx != null)tx.rollback();
                throw qae;
            }
            catch(Exception e)
            {
                //loginName,email,mobile are unique in database                
                log.error("add a new user:loginname,email,mobile="+userForm.getLoginName()+","+userForm.getEmail()+","+userForm.getMobile(),e);
                if (tx != null)tx.rollback();
                throw new QaException(e);
            }
            finally
            {
                HibernateSessionFactory.closeSession();
            }
            return user;
        }
	/**
         * change user's password
         * @param userId
         * @param newPassword
         * @param oldPassword
         * @return int 0 no user, 1 ok,2 old password not right
         * @throws QaException
         */
        private int changePassword(Integer userId,String newPassword,String oldPassword) throws QaException
        {
            Transaction tx = null;
            try
            {
                UserDAO userDAO = new UserDAO();            
                tx = HibernateSessionFactory.getSession().beginTransaction();            
                User user = userDAO.findById(userId);
                if(user == null)return 0;
                if(!user.getPassword().equals(oldPassword))return 2;
                user.setPassword(newPassword);
                userDAO.update(user);
                tx.commit();
                return 1;
            }
            catch (Exception  re)
            {
                if (tx != null)tx.rollback();            
                throw new QaException(re);
            }
            finally 
            {
                HibernateSessionFactory.closeSession();
            }
        }
        /**
         * autoLogin according to loginName and lastLoginDate
         * @param loginName(loginName/mobile/mail)
         * @param lastLogonDatetime the value is in cookie
         * @param logonDate
         * @return
         */
	public User autoLogin(String loginName, String lastLogonDatetime,Date logonDate)
        {
            User user = null;
	    Transaction tx = null;
            try
            {
	        log.info("user try to log on automatically in "+loginName);            
                UserDAO userDAO = new UserDAO();
                tx = HibernateSessionFactory.getSession().beginTransaction();
                List users = userDAO.findByLoginName(loginName);//1.loginName
                if(users.size() == 0)
                {
                    users = userDAO.findByEmail(loginName);//2.mail 2008.3.5
                    if(users.size() == 0)
                    {
                        users = userDAO.findByMobile(loginName);//3.mobile 2008.3.5
                    }
                }
                if(users.size() > 0) 
                {
                    user = (User) users.get(0);
                    if("1".equals(user.getState()))
                    {
                        log.info("user log on automatically in "+user.getId()+":"+loginName+", but the user's state is disabled");
                        throw new Exception();
                    }
                    String _lastLogonDatetime = (""+user.getLastLoginDate().getTime()).substring(0,10);
                    lastLogonDatetime = lastLogonDatetime.substring(0,10);
                    if(_lastLogonDatetime.equals(lastLogonDatetime)) 
                    {
                        user.setLastLoginDate(logonDate);
                        log.info("user log on automatically in "+user.getId()+":"+loginName);
                        //userDAO.update(user);//2008.12.13
                        //userDAO.addScoreHistory(user,null,"login","autologin");
                    }
                    else
                    {
                        log.info("Warn:user failed to log on automatically in "+user.getId()+":"+loginName+" because lastLogonDate on server is not equal to the one in cookie!");
                        user = null;
                    }
                }
                if(user != null)user.getNewMessages().size();
                //deleteOverMessages(user);
                tx.commit();
	    }
	    catch(Exception re)
	    {
                if (tx != null)tx.rollback();
	    }
	    finally
	    {
                HibernateSessionFactory.closeSession();
	    }
            return user;
	}
    
    /**
     * @deprecated
     * @param user
     */
    private void deleteOverMessages(User user) {
        Set list = user.getNewMessages();
        int count = list.size();
        if(count > MessageAction.MAX_MESSAGES) {
            Object[] messages = list.toArray();
            Message message = null;
            MessageDAO messageDAO = new MessageDAO();
            for(int i=MessageAction.MAX_MESSAGES;i<count;i++) {
                message = (Message)messages[i];
                list.remove(message);
                messageDAO.delete(message);
            }
            user.setNewMessages(list);
        }
        
    }
        
    /**
     * one session includes find and update
     * @param loginName(loginName/mobile/mail)
     * @param password
     * @return
     */
    private User doLogin(String loginName, String password,Date logonDate)
    {
        User user = null;
        Transaction tx = null;
        try
        {
            log.info("user try to log on in "+loginName);
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List users = userDAO.findByLoginName(loginName);//1.loginName
            if(users.size() == 0)
            {
                users = userDAO.findByEmail(loginName);//2.mail 2008.3.5
                if(users.size() == 0)
                {
                    users = userDAO.findByMobile(loginName);//3.mobile 2008.3.5
                }
            }
            if(users.size() > 0) 
            {
                user = (User) users.get(0);
                if(password.equals(user.getPassword()) && "0".equals(user.getState())) 
                {
                    user.setLastLoginDate(logonDate);
                    log.info("user log on in "+user.getId()+":"+loginName);
                    //userDAO.addScoreHistory(user,null,"login","login");
                }
                else
                {
                    log.info("Warn:user failed to log on in "+user.getId()+":"+loginName+" due to password dismatch");
                    user = null;
                }
            }
            if(user != null)user.getNewMessages().size();
            //deleteOverMessages(user);
            tx.commit();
        }
        catch(Exception re)
        {
            if (tx != null)tx.rollback();
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return user;
    }        
        
        private boolean goReferer(HttpServletRequest request)
        {
            String uri = request.getRequestURI();
            if(uri == null)uri = "";
            String referer = request.getHeader("Referer");
            if(referer.indexOf("user.mrqa") >= 0)
            {
                return false;
            }
            if(referer == null)return false;
            if(referer.indexOf("action=logout") > 0)
            {
              return false;  
            }
            else if(referer.indexOf("userlogin") > 0)
            {
                return false;
            }
            return true;
        }
 
        private void createUsersExcel(OutputStream os) throws QaException
        {
            String[] headerNames = {"Id","LoginName","Name","Email","Mobile"
            ,"RegisterDate","LastLogonDate","State","Type","Experience","Score","QuestionCount","AnswerCount"};
            ExcelWriter ew = new ExcelWriter(headerNames,"Iask User List");
            try
            {
                int total = this.countAllUsers();
                List users = this.getList(1,total);
                User user;
                Iterator ite = users.iterator();
                ExcelRow er = null;
                int i=0;
                while(ite.hasNext())
                {
                    i = 0;
                    user = (User)ite.next();
                    er = new ExcelRow(headerNames.length);
                    er.setCellData(i++,""+user.getId());
                    er.setCellData(i++,""+user.getLoginName());
                    er.setCellData(i++,""+user.getName());
                    er.setCellData(i++,""+user.getEmail());
                    er.setCellData(i++,""+user.getMobile());
                    er.setCellData(i++,""+user.getRegisterDate());
                    er.setCellData(i++,""+user.getLastLoginDate());
                    er.setCellData(i++,""+user.getState());                    
                    er.setCellData(i++,""+user.getType());
                    er.setCellData(i++,""+user.getUserScore().getTotalScore());
                    er.setCellData(i++,""+user.getUserMoney().getTotalMoney());
                    er.setCellData(i++,""+user.getQuestionsCount());
                    er.setCellData(i++,""+user.getAnswersCount());
                    ew.addRow(er);
                }
            }
            catch(Exception e)
            {
                log.error("looping users when creating excel exception:"+e);
                throw new QaException(e);
            }
            try
            {
                ew.export(os);
            }catch(Exception e)
            {
                log.error("export users when creating excel exception:"+e);
                throw new QaException(e);
            }
            
        }
 
        public static void printlnCookies(String where,HttpServletRequest request)
        {
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            String cookieNameValues = "";
            for(int i=0;i<cookies.length;i++)
            {
                cookie = cookies[i];
                cookieNameValues += cookie.getName()+":"+cookie.getValue()+",";
            }
            log.info(where+" Cookies:"+cookieNameValues);
        }
        
        /**
         * get count of my Shared files
         * @param userId
         * @return Shared files count
         */
        public Integer countMyShareFile(Integer userId) throws QaException{
        	Transaction tx = null;
            try
            {
                Integer count;
                tx = HibernateSessionFactory.getSession().beginTransaction();
                SharedFileDAO shareFileDAO = new SharedFileDAO();
                count = new Integer(shareFileDAO.countMylist(userId));
                tx.commit();
                return count;
            }
            catch(Exception e)
            {
                throw new QaException(e);
            }
            finally 
            {
                HibernateSessionFactory.closeSession();
            }
        }
        
        /**
         * get count of other's Shared files
         * @param userId
         * @return Shared files count
         */
        public Integer countHisShareFile(Integer userId) throws QaException{
        	Transaction tx = null;
            try
            {
                Integer count;
                tx = HibernateSessionFactory.getSession().beginTransaction();
                SharedFileDAO shareFileDAO = new SharedFileDAO();
                count = new Integer(shareFileDAO.countHislist(userId));
                tx.commit();
                return count;
            }
            catch(Exception e)
            {
                throw new QaException(e);
            }
            finally 
            {
                HibernateSessionFactory.closeSession();
            }
        }
        
        public void countHisQuestionAnswer(HttpServletRequest request, Integer userId) throws QaException{
        	Transaction tx = null;
        	try
            {
                Integer questionCount = countUserQuestions(userId);
                request.setAttribute("questionCount", questionCount);
                
                Integer answerCount = countUserAnswers(userId);
                request.setAttribute("answerCount", answerCount);
                
                Integer sharedFileCount = countHisShareFile(userId);
                
                request.setAttribute("sfCount", sharedFileCount);
                
        		Integer recommedQuestionCount = countHisRecommendQuestion(userId);
        		
        		MoneyReport moneyReport = new MoneyReport(userId, questionCount, answerCount, sharedFileCount, recommedQuestionCount);
        		moneyReport.calcuatePersonPoint();
        		Integer totalScore = moneyReport.getTotalScore();
                tx = HibernateSessionFactory.getSession().beginTransaction();
                UserDAO userdao = new UserDAO();
                User user = userdao.findById(userId);
                user.setQuestionsCount(questionCount);
                user.setAnswersCount(answerCount);
                user.getUserScore().setTotalScore(totalScore);
                
                UserMoneySpendHistoryDAO umshDAO = new UserMoneySpendHistoryDAO();
                Integer spendAmount = umshDAO.getUserSpendAmount(userId, null);
                user.getUserMoney().setTotalMoney(totalScore + spendAmount);
                
                request.setAttribute("usero",user);
        		tx.commit();
            }catch(Exception e)
            {
                throw new QaException(e);
            }
            finally 
            {
                HibernateSessionFactory.closeSession();
            }
        	
        }
        
     public Integer addHeaderImage(UserForm form, ActionMessages errors) throws QaException {
    	 Transaction tx = null;
    	 String strUserId = form.getId();
    	 Integer userId = Integer.valueOf(strUserId);
    	 String path = uploadHeader(form.getHeader(), form.getId(), errors);
    	 
    	 if (path != null && path.length() > 0) {

			try {
				// User user = userDAO.findById(userId);

				tx = HibernateSessionFactory.getSession().beginTransaction();
				UserDAO userDAO = new UserDAO();
				User user = userDAO.findById(userId);

				String headImage = user.getHeaderImage();
				if (headImage != null && headImage.length() > 0) {
					if (deleteOldImage(headImage)) {
						user.setHeaderImage(path);
					}
				}else{
					user.setHeaderImage(path);
				}

				tx.commit();
			} catch (Exception e) {
				if (tx != null)
					tx.rollback();
				throw new QaException(e);
			} finally {
				HibernateSessionFactory.closeSession();
			}
		}
    	return userId;
     }
        
     /**
	 * upload the header image
	 * 
	 * @param file
	 * @param errors
	 * @return file path
	 */
	public String uploadHeader(FormFile file, String id, ActionMessages errors) throws QaException {
		if (file == null)
			return null;
		String fileName = file.getFileName();
		if (fileName == null || fileName.length() == 0)
			return null;
		
		String ext = fileName.substring(fileName.lastIndexOf("."));
		if(!".jpg".equalsIgnoreCase(ext) && !".gif".equalsIgnoreCase(ext) && !".png".equalsIgnoreCase(ext)){
			errors.add("", new ActionMessage("imageheader.filename"));
			return null;
		}

		if (file.getFileSize() > GlobalConfigs.SIZE_HEADERIMAGE) {
			errors.add("", new ActionMessage("imageheader.oversize"));
			return null;
		}
		
		String newFileName = "";

		InputStream in;
		OutputStream out;
		try {
			in = file.getInputStream();
			String phisicalFile = "";
			newFileName = id + "_" + new java.util.Date().getTime() + ext;
			File dir = new File(getPhisicalHeaderDir());
			if(!dir.exists()){
				dir.mkdir();
			}
			phisicalFile = getPhisicalHeaderDir() + File.separator + newFileName;
			out = new FileOutputStream(phisicalFile);
			Util.copyStream(in, out);
			in.close();
			out.close();
		} catch (IOException e) {
			errors.add("", new ActionMessage("uploadfile.failure", fileName));
			log.error("add uploaded file into dir exception:" + e);
			throw new QaException(e);
		}
		return "/" + newFileName;
	}
        
        /**
         * 
         * @return the absolute path of header image, e.g./root/header(unix)
         */
        private String getPhisicalHeaderDir()
        {
            return GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION + UploadFileType.getPhysicalPath(UploadFileType.header);
        }
        
        /**
         * delete the old image if user update the image
         * @param imageFileName
         * @return boolean
         */
        private boolean deleteOldImage(String imageFileName){
        	File file = new File(getPhisicalHeaderDir() + File.separator + imageFileName);
        	return file.delete();
        }
        
        /**
         * get user by email
         * @param email
         * @return user
         */
        private User checkUserByEmail(String email) throws QaException{
        	return checkUserByEmail(email, null);
        }
        
        /**
         * get user by email
         * @param email
         * @return user
         */
        private User checkUserByEmail(String email, Integer userId) throws QaException{
        	Transaction tx = null;
            try
            {
            	User user = null;
                UserDAO userDAO = new UserDAO();
                tx = HibernateSessionFactory.getSession().beginTransaction();
                List list;
                if(userId == null){
                	list = userDAO.findByEmail(email);
                }else{
                	list = userDAO.findByEmaiExceptId(email, userId);
                }
                if(list != null && !list.isEmpty()){
                	user = (User)list.get(0);
                }
                tx.commit();
                return user;
            }
            catch(Exception e)
            {
                if(tx != null) 
                  tx.rollback();
                throw new QaException(e);
            }
            finally 
            {
                HibernateSessionFactory.closeSession();
            }
        }
        
        
        /**
         * @return the absolute path of shared file, e.g./root/sharedfile(unix)
         */
        private String getPhisicalUploadedFileDir(UploadFileType uploadFileType)
        {
        	return GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION + UploadFileType.getPhysicalPath(uploadFileType);
        }
        
        private String getPhisicalUploadedFileDir()
        {
        	return getPhisicalUploadedFileDir(UploadFileType.attachment);
        }
        
        

	/*private String getSysPassword() throws QaException {

		InputStream is = null;
		String password;
		try {
			//is = this.getClass().getClassLoader().getResourceAsStream(GlobalConfigs.SYSTEM_PROPERTY_FILE);
			String filePath = this.getClass().getResource("/").getPath() + GlobalConfigs.SYSTEM_PROPERTY_FILE;
			filePath = URLDecoder.decode(filePath, "UTF-8");
			//filePath = filePath.replaceAll("%20", " ");
			is = new FileInputStream(filePath);
			Properties props = new Properties();
			props.load(is);
			password = props.getProperty("adminPassword");
			return password;
		} catch (IOException e) {
			throw new QaException(e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ex) {
					throw new QaException(ex);
				}
			}
		}
	}*/
	
	private Integer countHisRecommendQuestion(Integer userId) throws QaException{
		Transaction tx = null;
        try
        {
            QuestionDAO questionDAO = new QuestionDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = questionDAO.countUserRecommendQuestions(userId);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
	
	private Integer countSharedFileDownloads(Integer userId) throws QaException{
		Transaction tx = null;
        try
        {
            SharedFileDAO sharedFileDAO = new SharedFileDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            int count = sharedFileDAO.countHislistDownloaded(userId);
            tx.commit();
            return count;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
	
	private void getSpendMoney(Integer userId, HttpServletRequest request, int page, int pageSize) throws QaException{
		Transaction tx = null;
        try
        {
            UserMoneySpendHistory userMoneySpendHistory = new UserMoneySpendHistory();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            Integer amount = userMoneySpendHistory.getUserSpendOnlyAmount(userId);
            
            Integer count = userMoneySpendHistory.countUserSpendOnly(userId);
            List list = userMoneySpendHistory.findUserSpendOnly(userId, page, pageSize);
            request.setAttribute("spendAmount", amount);
            request.setAttribute("spendList", list);
            request.setAttribute("pageSize",pageSize);//for pagination tag
            request.setAttribute("resultSize",count);//for pagination tag
            tx.commit();
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
	
	private void getAwardMoney(Integer userId, HttpServletRequest request, int page, int pageSize) throws QaException{
		Transaction tx = null;
        try
        {
            UserMoneySpendHistory userMoneySpendHistory = new UserMoneySpendHistory();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            Integer amount = userMoneySpendHistory.getUserAwardOnlyAmount(userId);
            
            Integer count = userMoneySpendHistory.countUserSpendOnly(userId);
            List list = userMoneySpendHistory.findUserAwardOnly(userId, page, pageSize);
            request.setAttribute("spendAmount", amount);
            request.setAttribute("spendList", list);
            request.setAttribute("pageSize",pageSize);//for pagination tag
            request.setAttribute("resultSize",count);//for pagination tag
            tx.commit();
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
	
	/*private Integer getPersonPoint(Integer userId) throws QaException{
		Integer questionCount = countUserQuestions(userId);
		Integer answerCount = countUserAnswers(userId);
		Integer sharedFileCount = countHisShareFile(userId);
		Integer recommedQuestionCount = countHisRecommendQuestion(userId);
		Integer sharedFileDownloadCount = countSharedFileDownloads(userId);
		return calcuatePersonPoint(questionCount, answerCount, sharedFileCount, recommedQuestionCount, sharedFileDownloadCount);
	}*/
	
	public String initPersonPoint() throws QaException{
		Transaction tx = null;
        try
        {
        	StringBuffer result = new StringBuffer();
            UserDAO userDAO = new UserDAO();
            userDAO.setPage(-1, -1);
            List<User> users = userDAO.getList();
            for(User user: users){
            	Integer userId = user.getId();
            	Integer questionCount = countUserQuestions(userId);
                
                Integer answerCount = countUserAnswers(userId);
                
                Integer sharedFileCount = countHisShareFile(userId);
                
        		Integer recommedQuestionCount = countHisRecommendQuestion(userId);
        		//Integer sharedFileDownloadCount = countSharedFileDownloads(userId);
        		
        		MoneyReport moneyReport = new MoneyReport(userId, questionCount, answerCount, sharedFileCount, recommedQuestionCount);
        		moneyReport.calcuatePersonPoint();
        		Integer totalScore = moneyReport.getTotalScore();
                tx = HibernateSessionFactory.getSession().beginTransaction();
                UserDAO userdao = new UserDAO();
                user = userdao.findById(userId);
                user.setQuestionsCount(questionCount);
                user.setAnswersCount(answerCount);
                UserScore score = user.getUserScore();
                score.setTotalScore(totalScore);
                user.setUserScore(score);
                
                UserMoney money = user.getUserMoney();
                if(money == null){
                	money = new UserMoney();
                	money.setMrIaskUser(user);
                	user.setUserMoney(money);
                }
                UserMoneySpendHistoryDAO umshDAO = new UserMoneySpendHistoryDAO();
                Integer spendAmount = umshDAO.getUserSpendAmount(userId, null);
                money.setTotalMoney(totalScore - spendAmount);
                user.setUserMoney(money);
                result.append("user: " + user.getLoginName() + ", point: " + totalScore + "<br />");
                tx.commit();
            }
            return result.toString();
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
  
	private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	
	private boolean checkIpIsForbidden(HttpServletRequest request){
		String ip = getIpAddr(request);
		boolean result = false;
		for (int i = 0; i < forbiddenIP.length; i++) {
			if(forbiddenIP[i].equals(ip)){
				return true;
			}
		}
		return result;
	}
	
	private User active(Integer userId) throws QaException{
		Transaction tx = null;
        try
        {
        	tx = HibernateSessionFactory.getSession().beginTransaction();
            UserDAO userDAO = new UserDAO();
            User user = userDAO.findById(userId);
            user.setIsActive(true);
            userDAO.save(user);
            tx.commit();
            return user;
        }
        catch(Exception e)
        {
            log.error("Exception:"+e+" when countUserQuestions");
            if(tx != null) 
                tx.rollback();
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
	}
	
	private boolean sendActiveMail(User user, String serverName, boolean isModify)
    {
        boolean sendOk = true;
        try
        {
        	String activeUrl = "http://" + serverName + "/user.mrqa?action=active&id=" + user.getId();
            Mail htmlMail = new Mail();
            htmlMail.setFrom("service@mainframer.cn");
            htmlMail.setTo(user.getEmail());
            //htmlMail.setCc("ytstcn@yahoo.com.cn");
            //htmlMail.setBcc("tao_shang@hotmail.com");
            //log.info("job title:"+jobTitle);
            htmlMail.setSubject("Welcome to Mainframer.cn");
            if (!isModify){
            	htmlMail.setBody("Hi "+ user.getLoginName() + "<br />感谢您关注mainframer.cn，请点击以下链接来激活您的账号<br /><a href=\"" + activeUrl + "\">" + activeUrl + "</a><br /><br />mainframer.cn");
            } else {
            	htmlMail.setBody("Hi "+ user.getLoginName() + "<br />您的email地址已改变。请点击以下连接来重新激活您的帐号<br /><a href=\"" + activeUrl 
            			+ "\">" + activeUrl + "</a><br /><br />mainframer.cn");
            }
            MailUtil.sendServiceSimpleHtmlMail(htmlMail);//?
            //log.info("send resume mail:"+file.getFileName()+" to "+adQuestionCategoryMail+" for applying for "+adQuestionCategoryName+"-"+jobTitle);
        }
        catch(QaException qe)
        {
            sendOk = false;
            log.error("send resume mail QaException:"+qe);
        }
        catch(Exception e)
        {
            sendOk = false;
            log.error("send resume mail Exception:"+e);
        }
        return sendOk;
    }
	
	private boolean sendActiveMailInModify(String email, Integer userId, String serverName) throws QaException{
    	Transaction tx = null;
    	boolean sendOK = false;
        try
        {
        	User user = null;
            UserDAO userDAO = new UserDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            List list;
            user = userDAO.findById(userId);
            if(user != null){
            	user.setEmail(email);
            	userDAO.save(user);
            	sendOK = sendActiveMail(user, serverName, false);
            }
            tx.commit();
            return sendOK;
        }
        catch(Exception e)
        {
            if(tx != null) 
              tx.rollback();
            throw new QaException(e);
        }
        finally 
        {
            HibernateSessionFactory.closeSession();
        }
    }
}